home *** CD-ROM | disk | FTP | other *** search
/ Freaks Macintosh Archive / Freaks Macintosh Archive.bin / Freaks Macintosh Archives / Ham⁄GPS / SoftKiss.src.1.8 Folder / SoftKiss.src.1.8.sit / SoftKiss.src.1.8 / lib / sfk_die.c next >
Text File  |  1993-03-08  |  1KB  |  53 lines

  1. /*
  2.  * roll an n sided die
  3.  */
  4.  
  5. #include "sfk_die.h"
  6.  
  7. #define MAXRAND 0x7fffffff
  8.  
  9. /*  die  --  roll an n-sided die
  10.  *|wohl use long instead of int
  11.  *
  12.  *  i = die (max)
  13.  *  long max;
  14.  *  returns a value from 0 to n-1, drawn from a random population with
  15.  *  even distribution.
  16.  *
  17.  *  Uses the random number generator (rand).  You must seed it with
  18.  *  srand().
  19.  *
  20.  *  Written by Steven Shafer and Tom Rodeheffer, August 1978.
  21.  *  Uses a Monte Carlo method; we have verified that it is not biased.
  22.  *
  23.  *  The maximum die value is MAXRAND, the largest number returned
  24.  *  from the random number geneator.
  25.  *
  26.  * HISTORY
  27.  * 06-Mar-80  Steven Shafer (sas) at Carnegie-Mellon University
  28.  *    Created.
  29.  *
  30.  */
  31. long die(long max)
  32. {
  33.     register unsigned long int binsize;        /* size of each of (max) bins */
  34.     register unsigned long int draw;        /* the number we drew from rng */
  35.     register unsigned long int minbad;        /* the smallest draw that's too big */
  36.  
  37. /* We divide the interval from 0 to MAXRAND into max "bins", each of
  38.  * equal size and as large as possible.  We draw a random number which
  39.  * must lie in a bin, and return the number of the bin into which
  40.  * it falls.
  41.  */
  42.  
  43.     if (max < 1)
  44.         return (0);
  45.  
  46.     binsize = MAXRAND / max;
  47.     minbad = max * binsize;        /* bigger than this is no good */
  48.  
  49.     do { draw = lrand(); } while (draw >= minbad);
  50.  
  51.     return (draw / binsize);
  52. }
  53.